package com.sxl.controller;

import com.alibaba.druid.sql.ast.statement.SQLForeignKeyImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxl.config.LayUiResult;
import com.sxl.domain.Askers;
import com.sxl.domain.Students;
import com.sxl.domain.Userroles;
import com.sxl.service.AskersService;
import com.sxl.service.StudentsService;
import com.sxl.service.UserrolesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @ProjectName: CRMProject
 * @Package: com.sxl.controller
 * @Author songxueliang
 * @Date 2022/4/18 12:28
 */
@RestController
@CrossOrigin
@RequestMapping("/userroles")
public class UserrolesController {
    @Autowired
    private UserrolesService userrolesService;
    @Autowired
    private AskersService askersService;
    @Autowired
    private StudentsService studentsService;
    /**
     * 查询用户都有什么角色
     * @param uid
     * @return
     */
    @PostMapping("/selectUserrolesById")
    public List<Userroles> selectById(Integer uid){
        return userrolesService.selectUserrolesById(uid);
    }

    /**
     * 给用户添加角色
     * @param userroles
     * @return
     */
    @PostMapping("/AddUserroles")
    public Map<String,Object> AddUserroles(Userroles userroles){
        boolean save = userrolesService.save(userroles);
        List<Userroles> userroles1 = userrolesService.selectUserAndUserrolesAndRolesById(userroles.getUserId());
        for(Userroles u : userroles1){
            if (u.getName().equals("咨询师")){
                Askers a =new Askers();
                a.setAskerId(u.getUserId());
                a.setAskerName(u.getLoginName());
                askersService.save(a);
            }
        }
        return save==true ?LayUiResult.toClient("0","设置成功"):LayUiResult.toClient("1","设置失败");
    }

    /**
     * 删除用户角色
     * @param userId
     * @param roleId
     * @return
     */
    @PostMapping("/deleteUserroles")
    public Map<String,Object> deleteUserroles(Integer userId, Integer roleId){
        QueryWrapper<Students> wrapper =new QueryWrapper();
        wrapper.eq("askerId",userId);
        List<Students> list = studentsService.list(wrapper);
        if (list!=null && list.size()>0){
            return LayUiResult.toClient("1","该咨询师下还有学生，不能移除该角色");
        }else {
            askersService.deleteByAskerId(userId);
        }
        int i = userrolesService.deleteUserroles(userId, roleId);
        return i>0 ?LayUiResult.toClient("0","设置成功"):LayUiResult.toClient("1","设置失败");
    }

}
